package kr.co.bettersoft.usedmarketandroid.fragment;


import java.util.List;
import java.util.Locale;

import com.google.android.gcm.GCMRegistrar;

import kr.co.bettersoft.usedmarketandroid.activity.GCMIntentService;
import kr.co.bettersoft.usedmarketandroid.activity.R;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketChatRoomActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketChatRoomListActivity;
import kr.co.bettersoft.usedmarketandroid.common.CommonConstant;
import kr.co.bettersoft.usedmarketandroid.common.UsedMarketChatRest;
import kr.co.bettersoft.usedmarketandroid.common.UsedMarketRest;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChat;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChatUser;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketSMS;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * FragmentHome
 *  프래그먼트 홈
 *  TabActivity 를 Fragment 방식으로 대체하면서 TabActivity 기능을 구현한 FragmentActivity 이며
 *   채팅리스트, 다이어리리스트,멤버리스트,더보기 등을 기존 탭 메뉴가 아닌 fragment 로 추가시켜서 사용 
 * @author blue
 *
 */
public class FragmentMain extends FragmentActivity{

	static String TAG = "FragmentHome";

	public static Activity fragmentHome ;

	TabHost tHost;
	
	ProgressBar pb1;
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	final int REGISTER_CHAT_AND_REGISTER_USER = 101;		// registerChatAndRegisterUser 
//	final int SELECT_CHAT_LIST = 102;		// selectChatList 
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// ###

	FragmentMenu1Home fragmentMenu1Home;
	FragmentMenu2Category fragmentMenu2Category;
	FragmentMenu3MyShop fragmentMenu3MyShop;
	FragmentMenu4Community fragmentMenu4Community;
	FragmentMenu5Settings fragmentMenu5Settings;

	// 마지막으로 들어간 프래그먼트의 태그값		 
	String lastMenuPushed = "";

	// 선택된 탭, 선택되지 않은 탭 색상 구분
	String BACKGROUND_COLOR_NOT_SELECTED = "#DCDCDC";			
	String BACKGROUND_COLOR_SELECTED = "#A9A9A9";	
	String TEXT_COLOR_NOT_SELECTED = "#000000";			
	String TEXT_COLOR_SELECTED = "#FFFFFF";	

	int nowMenuPostion = 0;	// 같은 화면 두번 호출방지		
	Boolean isSame = false;

	int firstFragmentId;		// 뒤로가기 버튼에 대한 상호 작용을 위해 첫번째 fragment 의 아이디값을 저장.

	// 공용 프립스
	SharedPreferences sharedPrefCustom;		

	//gcm
	AsyncTask<Void, Void, Void> mRegisterTask;

	public String phoneNum;

	
	
	// 전달받은 값
	String idUsedMarketProduct;
	String othersPhoneNumber;
	
	// 채팅방 정보
	UsedMarketChat usedMarketChatRoomInfo;
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		// 받아온결과를 화면에 뿌려준다.

				
				
				// 화면에 알림창
				if(b.getInt("showAlert")==1){					 // 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							 
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							//
						}})
						.setNegativeButton("", null).show();
				}
				
				// 채팅방 생성 이동 알림
				if(b.getInt("showAlertAndGoChatRoom")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							Intent intent = new Intent(FragmentMain.this, UsedMarketChatRoomActivity.class);
							intent.putExtra("usedMarketChatIdUsedMarketChat", usedMarketChatRoomInfo.getIdUsedMarketChat());	
							intent.putExtra("usedMarketChatIdUsedMarketProduct", usedMarketChatRoomInfo.getIdUsedMarketProduct());	
							intent.putExtra("usedMarketChatOwner", usedMarketChatRoomInfo.getOwner());	
							intent.putExtra("subject", usedMarketChatRoomInfo.getSubject());		// ### 	
							startActivity(intent);
						}})
						.setNegativeButton("", null).show();
				}
				
				// 종료 확인
				if(b.getInt("confirmFinish")==1){					 // 앱 종료 확인
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}})
						.setNegativeButton(android.R.string.no, null).show();
				}
				
				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.GONE);
				}
				
				switch (msg.what)
				{
					case REGISTER_CHAT_AND_REGISTER_USER : runOnUiThread(new RunnableRegisterChatAndRegisterUser());		
						break;
//					case SELECT_CHAT_LIST : runOnUiThread(new RunnableSelectChatList());		
//						break;
//					case NICK_NAME_DUPLICATION_CHECK : runOnUiThread(new RunnableSelectDuplicationNickNameBeforeRegister());
//					break;
//					case REGISTER_MEMBER : runOnUiThread(new RunnableRegisterMemberToServer());		
//					break;
					default : 
						break;
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};


	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////		

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.fragment_main);

		
		pb1 = (ProgressBar) findViewById(R.id.progressbar1);
		
		/*
		 * 전화번호 체크하여 GCM 업데이트
		 */
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		// prefs
		phoneNum = sharedPrefCustom.getString("phoneNum", "");
		
		// update GCM
		if(phoneNum.length()>0){
			nextProcessing();
		}
		
		/*
		 * fragment 생성
		 */
		fragmentMenu1Home = new FragmentMenu1Home();
		fragmentMenu2Category = new FragmentMenu2Category();
		fragmentMenu3MyShop = new FragmentMenu3MyShop();
		fragmentMenu4Community = new FragmentMenu4Community();
		fragmentMenu5Settings = new FragmentMenu5Settings();
		

		/*
		 * 탭 메뉴와 fragment 세팅
		 */
		tHost = (TabHost) findViewById(android.R.id.tabhost);
		tHost.setup();
		
		
		/*
		 * 탭 위젯 세팅
		 */
		/** Defining tab builder for 홈 tab */
		TabHost.TabSpec tSpecHome = tHost.newTabSpec("fragmentMenu1Home");
		tSpecHome.setIndicator("홈",getResources().getDrawable(R.drawable.fragment_home));        
		tSpecHome.setContent(new DummyTabContent(getBaseContext()));        
		tHost.addTab(tSpecHome);

		/** Defining tab builder for 카테고리 tab */
		TabHost.TabSpec tSpecCategory = tHost.newTabSpec("fragmentMenu2Category");
		tSpecCategory.setIndicator("카테고리",getResources().getDrawable(R.drawable.fragment_category));        
		tSpecCategory.setContent(new DummyTabContent(getBaseContext()));
		tHost.addTab(tSpecCategory);

		/** Defining tab builder for 내상점 tab */
		TabHost.TabSpec tSpecMyshop = tHost.newTabSpec("fragmentMenu3MyShop");
		tSpecMyshop.setIndicator("내상점",getResources().getDrawable(R.drawable.fragment_myshop));        
		tSpecMyshop.setContent(new DummyTabContent(getBaseContext()));
		tHost.addTab(tSpecMyshop);

		/** Defining tab builder for 커뮤니티 tab */
		TabHost.TabSpec tSpecCommunity = tHost.newTabSpec("fragmentMenu4Community");
		tSpecCommunity.setIndicator("커뮤니티",getResources().getDrawable(R.drawable.fragment_community));        
		tSpecCommunity.setContent(new DummyTabContent(getBaseContext()));
		tHost.addTab(tSpecCommunity);

		/** Defining tab builder for 설정 tab */
		TabHost.TabSpec tSpecSettings = tHost.newTabSpec("fragmentMenu5Settings");
		tSpecSettings.setIndicator("설정",getResources().getDrawable(R.drawable.fragment_settings));        
		tSpecSettings.setContent(new DummyTabContent(getBaseContext()));
		tHost.addTab(tSpecSettings);

		// 탭 위젯 배경 설정
		setTabColor(tHost);

		
		/*
		 * 탭 위젯 리스너
		 */
		/** Defining Tab Change Listener event. This is invoked when tab is changed */
		TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {

				showDetailFragment(tabId);		// ### 
				
				setTabColor(tHost);
			}
		};
		
		/** Setting tabchangelistener for the tab */
		tHost.setOnTabChangedListener(tabChangeListener);
		
		/*
		 * 첫화면 호출
		 */
		showDetailFragment("Menu1");
		
		
		// 저장용 값 변경해주기
		SharedPreferences.Editor saveChatRoomStatusPref = sharedPrefCustom.edit();
		saveChatRoomStatusPref.putBoolean("appRunningYn", true);			   		// 앱 실행중	
		saveChatRoomStatusPref.commit();
	}   


	/*
	 * fragment 이동시 호출.
	 */
	private void showDetailFragment(String fragmentTag)
	{

		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		
		Fragment newFragment = fragmentMenu1Home;

		
		Log.d(TAG,"fragmentTag:"+fragmentTag);
		if (fragmentTag.contains("Menu1")) {
			if(nowMenuPostion!=1){
				nowMenuPostion = 1;

				newFragment = fragmentMenu1Home;		

				isSame = false;
			}else{
				isSame = true;
			}
		}else if(fragmentTag.contains("Menu2")){
			if(nowMenuPostion!=2){
				nowMenuPostion = 2;

				newFragment = fragmentMenu2Category;			

				isSame = false;
			}else{
				isSame = true;
			}


		}else if(fragmentTag.contains("Menu3")){
			if(nowMenuPostion!=3){
				nowMenuPostion = 3;
				newFragment = fragmentMenu3MyShop;	

				isSame = false;
			}else{
				isSame = true;
			}
		}else if(fragmentTag.contains("Menu4")){
			if(nowMenuPostion!=4){
				nowMenuPostion = 4;
				newFragment = fragmentMenu4Community;			

				isSame = false;
			}else{
				isSame = true;
			}
		}else if(fragmentTag.contains("Menu5")){
			if(nowMenuPostion!=5){
				nowMenuPostion = 5;
				newFragment = fragmentMenu5Settings;	

				isSame = false;
			}else{
				isSame = true;
			}
		}else{
			nowMenuPostion = 1;

			newFragment = fragmentMenu1Home;		

			isSame = false;
		}

		if(!isSame){

			// reload 방지 이동
			showMenuFragment(newFragment, fragmentTag, true);

			// 로그 용
			if(nowMenuPostion == 1){
				Log.d(TAG,"newFragment::"+newFragment.getId());
				firstFragmentId = newFragment.getId();
			}
		}else{
			// reload 방지 이동
			showMenuFragment(newFragment, fragmentTag, false);
		}
	}
	
	
	/*
	 * fragment 간 이동시 reload 방지하기
	 */
	public void showMenuFragment( Fragment fragment, String tag, boolean addToBackStack ) {
		showFragment( R.id.realtabcontent, fragment, tag, getLastMenuPushed(), addToBackStack );		//details realtabcontent
		setLastMenuPushed( tag );
	}
	public String getLastMenuPushed(){
		return lastMenuPushed;
	}
	public void setLastMenuPushed(String tag){
		lastMenuPushed = tag;
	}
	protected void showFragment( int resId, Fragment fragment, String tag, String lastTag, boolean addToBackStack ) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();

		if ( lastTag != null ) {
			Fragment lastFragment = fragmentManager.findFragmentByTag( lastTag );
			if ( lastFragment != null ) {
				transaction.hide( lastFragment );
			}
		}
		if ( fragment.isAdded() ) {
			transaction.show( fragment );
		}
		else {
			transaction.add( resId, fragment, tag ).setBreadCrumbShortTitle( tag );
		}

		if ( addToBackStack ) {
			transaction.addToBackStack( tag );
		}

		transaction.commit();
	}

	
	/**
	 * 탭 위젯 배경 색상, 텍스트 색상 변경
	 *   선택된 탭과 선택되지 않은 탭을 구분하여 표시하기 위함
	 * @param tabhost
	 */
	public void setTabColor(TabHost tabhost) {

		// 전체 탭 초기화
		for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) {
			tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor(BACKGROUND_COLOR_NOT_SELECTED)); //unselected FF0000 DCDCDC			BACKGROUND_COLOR_NOT_SELECTED		BACKGROUND_COLOR_SELECTED

			TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
			tv.setTextColor(Color.parseColor(TEXT_COLOR_NOT_SELECTED));		// 000000     	TEXT_COLOR_NOT_SELECTED
		}
		
		// 선택된 탭 구분
		tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor(BACKGROUND_COLOR_SELECTED)); // selected 0000FF A9A9A9  

		TextView tv = (TextView) tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).findViewById(android.R.id.title);
		tv.setTextColor(Color.parseColor(TEXT_COLOR_SELECTED));		// FFFFFF	TEXT_COLOR_SELECTED
	}


	
	/**
	 * nextProcessing
	 *  GCM 세팅하여 등록한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void nextProcessing(){
		////////////////////////////////////////////GCM 세팅        ///////////////////////////////////////////////////////////////		
		GCMRegistrar.checkDevice(this);					// 임시 중지  ->해제
		GCMRegistrar.checkManifest(this);				
		Log.i(TAG, "registerReceiver1 ");
		mRegisterTask = new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {	// 무조건 GCM 등록한다. 이전값이든 새값이든 등록하고 //등록 결과를 서버에 업뎃하는 부분은 GCM서비스에서 처리한다.
				GCMRegistrar.register(returnThis(), CommonConstant.GCM_ID);	
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				mRegisterTask = null;
			}
		};
		mRegisterTask.execute(null, null, null);
	}
	
	/**
	 * getThis
	 *  컨택스트 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return this;
	}
	
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// 자체 함수
	
	/**
	 * 채팅방 생성
	 *   test 용. 40~45 // 01073584140
	 */
	public void createChatRoom(String idUsedMarketProduct, String othersPhoneNumber){
		phoneNum = sharedPrefCustom.getString("phoneNum", "");
		this.idUsedMarketProduct = idUsedMarketProduct;
		this.othersPhoneNumber = othersPhoneNumber;
		if(phoneNum!=null && phoneNum.length()>0 && idUsedMarketProduct!=null && idUsedMarketProduct.length()>0 && othersPhoneNumber!=null && othersPhoneNumber.length()>0){
			handler.sendEmptyMessage(REGISTER_CHAT_AND_REGISTER_USER);
//			new backgroundThreadRegisterChatAndRegisterUser().execute();	
		}else{
			// 오류
		}
	}
	
	/**
	 * 채팅방 리스트 불러오기 ##{@link #addContentView(View, android.view.ViewGroup.LayoutParams)}
	 *   
	 */
	public void selectChatList(){
		phoneNum = sharedPrefCustom.getString("phoneNum", "");
		if(phoneNum!=null && phoneNum.length()>0){
			Intent intent = new Intent(FragmentMain.this, UsedMarketChatRoomListActivity.class);
			startActivity(intent);
		}else{
			Log.d(TAG,"no phoneNum");
			// 오류
		}
	}
	
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// 서버 통신
	
	/**
	 * 러너블. 채팅방을 생성한다. 생성자를 사용자로 등록 한다.				registerChatAndRegisterUser
	 */
	class RunnableRegisterChatAndRegisterUser implements Runnable {
		public void run(){
			new backgroundThreadRegisterChatAndRegisterUser().execute();
		}
	}
	/**
	 * backgroundThreadRegisterChatAndRegisterUser
	 * 비동기    서버와 통신하여 채팅방을 생성한다. 생성자를 사용자로 등록 한다.	
	 * @author blue
	 *
	 */
	public class backgroundThreadRegisterChatAndRegisterUser extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadRegisterChatAndRegisterUser");
			
			// 파라미터 세팅
			UsedMarketChat usedMarketChat = new UsedMarketChat();
			usedMarketChat.setIdUsedMarketProduct(idUsedMarketProduct);		// 물품 테이블 아이디. -- 전달 받은 값.
			usedMarketChat.setOwner(phoneNum);				// 생성자 휴대전화번호.
			usedMarketChat.setPhoneNumber(phoneNum);		// 사용자(생성자) 휴대전화번호.

			// 서버 메소드 호출
			showPb();
			
			UsedMarketChatRest usedMarketChatRest = new UsedMarketChatRest();
			
			// 1단계. 채팅방 생성.
			UsedMarketChat resultUsedMarketChat = new UsedMarketChat();
			resultUsedMarketChat = usedMarketChatRest.RestRegisterChatAndRegisterUser(usedMarketChat);
//			Log.d(TAG,"backgroundThreadRegisterChatAndRegisterUser 1 result::"+resultUsedMarketChat.getResult());
			
			// 채팅방 생성 성공.
			if(resultUsedMarketChat.getResult().equals("SUCCESS")){
				Log.d(TAG,"create chat room SUCCESS");
				// 2단계. 채팅방 정보를 가져온다.
				usedMarketChat = new UsedMarketChat();
				usedMarketChat.setOwner(phoneNum);
				
				usedMarketChatRoomInfo = usedMarketChatRest.RestSelectChat(usedMarketChat);
//				Log.d(TAG,"backgroundThreadRegisterChatAndRegisterUser 2 result::"+resultUsedMarketChat2.getResult());

				if(usedMarketChatRoomInfo.getResult().equals("SUCCESS")){
					Log.d(TAG,"select chat room SUCCESS");
					// 3단계. 채팅방에 상대방을 추가한다. usedMarketChatUserController  registerUser
					UsedMarketChatUser usedMarketChatUser = new UsedMarketChatUser();
					usedMarketChatUser.setPhoneNumber(othersPhoneNumber);
					usedMarketChatUser.setUsedMarketChatIdUsedMarketChat(usedMarketChatRoomInfo.getIdUsedMarketChat());
					usedMarketChatUser.setUsedMarketChatIdUsedMarketProduct(usedMarketChatRoomInfo.getIdUsedMarketProduct());
					usedMarketChatUser.setUsedMarketChatOwner(usedMarketChatRoomInfo.getOwner());
					
//					UsedMarketChatUser resultUsedMarketChatUser3 = usedMarketChatRest.RestRegisterUser(usedMarketChatUser);
					String resultUsedMarketChatUser3 = usedMarketChatRest.RestRegisterUser(usedMarketChatUser);

//					Log.d(TAG,"backgroundThreadRegisterChatAndRegisterUser 3 result::"+resultUsedMarketChatUser3);

					if(resultUsedMarketChatUser3.equals("SUCCESS")){
						
						/*
						 * 채팅방 내에서 채팅방 정보를 가져올 수 없도록 구성되어있음. limit 1 제한으로 인해 방금 생성한 방의 정보만 가져와짐.
						 *  따라서 채팅방에서 정보를 가져오지 않고 만들고 나서 정보를 가져오도록 함.
						 */
						// ### 
						usedMarketChat = new UsedMarketChat();
						usedMarketChat.setOwner(phoneNum);
						//							selectChat	채팅방 정보를 가져 온다.	
						// 호출
						UsedMarketChat callResult = usedMarketChatRest.RestSelectChat(usedMarketChat);		

						// 결과 처리		 
						if(callResult.getResult().equals("SUCCESS")){ 
						//								Log.d(TAG,"callResult:"+callResult);
							
							// 제목 저장
							usedMarketChatRoomInfo.setSubject(callResult.getSubject());
							
							// 알림창을 띄우고 채팅방으로 이동한다.
							showAlertAndGoChatRoom("채팅방을 생성하였습니다.");	
							//							showResultDialog("인증 요청이 성공하였습니다.");	
							//							showAlert("채팅방 생성에 실패하였습니다.");

						}else{
							// 실패.
							showAlert("채팅방 생성에 실패하였습니다.");
						}
					}else{
						// 실패.
						showAlert("채팅방 생성에 실패하였습니다.");
					}

					
				}else{
					// 실패.
					showAlert("채팅방 생성에 실패하였습니다.");
				}
				
			}else{
				// 실패.
				showAlert("채팅방 생성에 실패하였습니다.");
			}
			hidePb();
			return null; 
		}
	}
	
	
	
//	/**
//	 * 러너블. 채팅방 목록을 가져 온다.			selectChatList
//	 */
//	class RunnableSelectChatList implements Runnable {
//		public void run(){
//			new backgroundThreadSelectChatList().execute();
//		}
//	}
//	/**
//	 * backgroundThreadSelectChatList
//	 * 비동기    서버와 통신하여 채팅방 목록을 가져 온다.
//	 * @author blue
//	 *
//	 */
//	public class backgroundThreadSelectChatList extends AsyncTask<Void, Void, Void>{
//		@Override protected void onPostExecute(Void result) {  
//		} 
//		@Override protected void onPreExecute() {  
//		} 
//		@Override protected Void doInBackground(Void... params) {  
//			Log.d(TAG,"backgroundThreadSelectChatList");
//			
//			// 파라미터 세팅
//			UsedMarketChat usedMarketChat = new UsedMarketChat();
//			usedMarketChat.setPhoneNumber(phoneNum);		// 사용자(생성자) 휴대전화번호.
//
//			// 서버 메소드 호출
//			showPb();
//			
//			UsedMarketChatRest usedMarketChatRest = new UsedMarketChatRest();
//			
//			UsedMarketChat resultUsedMarketChat = new UsedMarketChat();		// resultUsedMarketChat
//			String resultStr = usedMarketChatRest.RestSelectChatList(usedMarketChat);
//			Log.d(TAG,"backgroundThreadSelectChatList result::"+resultStr);
////			Log.d(TAG,"backgroundThreadSelectChatList result::"+resultUsedMarketChat.getResult());
////			if(resultUsedMarketChat.getResult().equals("SUCCESS")){
////				// 성공.
//////				showResultDialog("인증 요청이 성공하였습니다.");	
////			}else{
////				// 실패.
//////				showResultDialog("인증 요청이 실패하였습니다.");
////			}
//			hidePb();
//			return null; 
//		}
//	}
	
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// 사용자 알림
	/**
	 * showAlert
	 * 얼럿창을 띄운다
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlert(final String msg){
		runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlert", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	
	/**
	 * showAlertAndGoChatRoom
	 *  채팅방 생성 성공 알림 및 이동 
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlertAndGoChatRoom(final String msg){
		runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlertAndGoChatRoom", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 유틸	

	
	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	
	
	
	/**
	 * onBackPressed
	 *   백 버튼 으로 종료 한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onBackPressed() {
		Log.d(TAG, "FragmentHome finish");
		// ### 
		if(nowMenuPostion==1){
			fragmentMenu1Home.goBack();
		}else if(nowMenuPostion==2){
			fragmentMenu2Category.goBack();
		}else if(nowMenuPostion==3){
			fragmentMenu3MyShop.goBack();
		}else if(nowMenuPostion==4){
			fragmentMenu4Community.goBack();
		}else if(nowMenuPostion==5){
			confirmFinish();	
		}
	}

	/**
	 * confirmFinish
	 *  앱 종료 확인받기
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void confirmFinish(){			 
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("confirmFinish", 1);
						b.putString("msg", "종료하시겠습니까?");
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 


	@Override
	public void onDestroy(){
		SharedPreferences.Editor appRunningYnPref = sharedPrefCustom.edit();
		appRunningYnPref.putBoolean("appRunningYn", false);		// 실행중 아님.
		appRunningYnPref.commit();
		super.onDestroy();
		System.exit(0);
	}
}